<?php

namespace App\Http\Controllers;

use App\Models\ReadNotice;
use App\Models\Setting;
use Illuminate\Http\Request;

class NoticeController extends Controller
{
    /**
     * 获取系统公告
     */
    public function show()
    {
        try{
            $Setting = Setting::select("notice","notice_time")->first();
            if(empty(trim($Setting->notice))) {
                throw new \Exception("",402);
            }
            $_read_time = ReadNotice::where("member_id",auth("member")->id())
                ->value("time");
            if($_read_time && $Setting->notice_time == $_read_time) {
                throw new \Exception("",402);
            }
            return response(['data'=>$Setting->notice]);
        }catch (\Exception $e) {
            return response(["message"=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     *确认已读系统公告
     */
    public function store()
    {
        $_member_id = auth("member")->id();
        $_notice_time = Setting::value("notice_time");
        $ReadNotice = ReadNotice::where("member_id",$_member_id)
            ->select("id")->first();
        if($ReadNotice) {
            $_result = ReadNotice::where("id",$ReadNotice->id)->update([
                "time" => $_notice_time
            ]);
        } else {
            $_result = ReadNotice::create([
                "member_id" => $_member_id,
                "time" => $_notice_time
            ]);
        }
        return $_result ? response(['data'=>'success']) : response(['message'=>'操作失败'],402);
    }
}
